/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation for Parameter interface client library.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 * $Id: ParameterClient.cpp,v 1.2 2009-10-23 13:56:43 morsko Exp $
 *
 */

#include "ParameterClient.hpp"
#include "ParameterData.hpp"

//*****************************************************************************
using namespace MaCI::Parameter;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CParameterClient::CParameterClient(gimi::GIMI *aGIMIPtr, 
                                   const int aInterfaceMinor)
  : CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_PARAMETER, aInterfaceMinor)
{
  dPrint(4,"CParameterClient %p constructed", this);
}
//*****************************************************************************

CParameterClient::~CParameterClient()
{
  DoClose();
  dPrint(4,"CParameterClient %p destructed", this);
}
//*****************************************************************************

bool CParameterClient::GetParameterList(TParameterInfoArray &aParameterList,
                                        const unsigned int aTimeout_ms)
{
  bool result = true;
  if(IsActive()){

    CParameterData commandData;
    CParameterData replyData;
    commandData.CreateInternalBinBag();
    replyData.CreateInternalBinBag();
    SMessageSource ms; 
    // Get unique MessageID.
    const unsigned int  queryID = GetUniqueMessageID();
    // Construct Data element with Timestamp, Query and Command.
    result &= commandData.SetTimestamp(Common::TTimestamp());
    result &= commandData.SetCommand(TCommand(KCommandGetParameters));
    if (result) {
      
      result = (SendInterfaceMessage(commandData,queryID)==KMaCIOK);
      if(result){
        
        result = (ReceiveSynchronousMessageReply(replyData, ms,queryID, aTimeout_ms) == KMaCIOK);
        if(result){
        
          
          if(replyData.GetCommand()->cmd == KCommandGetParametersReply){
            const TParameterXML *pxmlstring = replyData.GetParameterXML();
            CParameterXML pxml;
            pxml.DecodeParameterXML(std::string(pxmlstring->GetTextPtr()));
            result = pxml.GetParameters(aParameterList);
           
            
            
          }else{
            dPrint(1,"Wrong command : '%d'. (should be '%d')",replyData.GetCommand()->cmd,KCommandGetParametersReply);
            result = false;
          }
          
          
        }else{
          dPrint(1,"No response within timeout time");
          result = false;
        }
        
      }
    } else {
      dPrint(ODERROR,"Failed to construct ParameterData container with given parameters! Nothing sent.");
      
    }
  }else{
    dPrint(3,"Client not opened yet! Could not get parameter list");
    result = false;
  }
  
  return result;
}
//*****************************************************************************

bool CParameterClient::SetParameter(const TParam &aParameterToSet)
{
  
  bool result = true;
  if(IsActive()){
    CParameterData commandData;
    commandData.CreateInternalBinBag();
    // Construct Data element with Timestamp, Query and Command.
    result &= commandData.SetTimestamp(Common::TTimestamp());
    result &= commandData.SetCommand(TCommand(KCommandSetParameter));
    int queryID = GetUniqueMessageID();
    //Construct XML
    CParameterXML pxml;
    pxml.SetParameter(aParameterToSet);
    std::string encodedString;
    pxml.EncodeParameterXML(encodedString);
    //Set it to CParameterData
    result &= commandData.SetParameterXMLString(encodedString);
  
    if (result) {
      result = (SendInterfaceMessage(commandData.GetBinBagContainerPtr()->GetBuffer(),
                                     commandData.GetBinBagContainerPtr()->GetBufferSize(),
                                     queryID) == KMaCIOK);
    } else {
      dPrint(ODERROR,"Failed to construct ParameterData container with given parameters! Nothing sent.");
      
    }
  }else{
    dPrint(3,"Client not opened yet! Could not get parameter list");
    result = false;
  }
  
  return result;




}
//*****************************************************************************
         
MaCI::EMaCIError CParameterClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
     
      SetActive(true);
      EnableSynchronousMessageReply();
    
      dPrint(4,"CParameterClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"ParameterClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************
 
MaCI::EMaCIError CParameterClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);
    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed ParameterClient");    
    }else{
      dPrint(4,"Unsubscribing failed at ParameterClient!");
    }
    
    result = KMaCIOK;
    
  } else {
    dPrint(4, "ParameterClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
